package com.fs.web;

import com.alibaba.fastjson.JSONObject;
import com.fs.utils.ImgInfo;
import com.fs.utils.ImgResult;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet("/fileControl/*")
public class FileServlet extends HttpServlet {

    private HttpServletRequest req;
    private HttpServletResponse resp;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



        this.req = request;
        this.resp = response;

        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        switch (req.getPathInfo()) {
            case "/upload": upload();break;
        }

    }

    private void upload() {
        //实例化本地磁盘工厂

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        //实例化文件上传类
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

        //获取前端上传文件列表
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);

            for(FileItem item : fileItems){


                    //文件名
                    String filename= item.getName();

                    filename = UUID.randomUUID().toString().replaceAll("-","") + filename.substring(filename.lastIndexOf('.'));


                    //将文件转存入本地路径

                    File file = new File("D://upload");

                    //不存在则创建
                    if(!file.exists())
                        file.mkdirs();

                    //写入本地路径
                    item.write(new File(file.getAbsolutePath()+"//"+filename));

                    String protocalSufix = req.getRequestURL().toString().replace(req.getRequestURI(),"");
                    String imgUrl = protocalSufix + "/file/" + filename;


                    ImgInfo imgInfo = new ImgInfo(imgUrl, filename, imgUrl);
                    resp.getWriter().print(JSONObject.toJSONString(ImgResult.success(imgInfo)));

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
